<template>
  <div>
    <van-nav-bar title="个人资料" left-text="返回" left-arrow @click-left="$router.back()" />
    <el-upload
      class="avatar-uploader"
      action="http://localhost:3000/lx/upload"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>

    <div style="margin-top: 50px">
      <van-cell-group inset>
        <van-field v-model="value1" label="用户名" placeholder="请输入用户名" />
        <van-field v-model="value2" label="性别" placeholder="请输入性别" />
        <van-field v-model="value3" label="年龄" placeholder="请输入年龄" />
        <van-field v-model="value4" label="家乡" placeholder="请输入家乡" />
        <van-field v-model="value5" label="行业" placeholder="请输入行业" />
      </van-cell-group>
      <van-button type="primary" style="margin-top: 50px" size="large" block @click="submitForm">
        提交
      </van-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'

// 定义响应式变量
const value1 = ref('') // 用户名
const value2 = ref('') // 性别
const value3 = ref('') // 年龄
const value4 = ref('') // 家乡
const value5 = ref('') // 行业
const imageUrl = ref('') // 头像 URL

const user = JSON.parse(localStorage.getItem('user') || '{}') // 从 localStorage 获取用户信息
const id = user._id || '' // 用户的 _id

// 获取用户信息
const getList = async () => {
  try {
    const response = await axios.get(`http://localhost:3000/lx/getuser?id=${id}`)
    console.log(response.data.data[0]);
    
    if (response.data.code === 200) {
      const userData = response.data.data[0]
      value1.value = userData.admin || ''
      value2.value = userData.sex || ''
      value3.value = userData.age || ''
      value4.value = userData.address || ''
      value5.value = userData.work || ''
      imageUrl.value = userData.landlord || '' // 设置头像 URL
    }
  } catch (error) {
    ElMessage.error('获取用户信息失败')
    console.error(error)
  }
}

// 处理头像上传成功
const handleAvatarSuccess = (response: any) => {
  imageUrl.value = response.data // 更新头像 URL
}

// 在组件加载时获取用户信息
onMounted(() => {
  getList() // 获取用户信息并渲染
  localStorage.setItem('user', JSON.stringify({ _id: '6729d8e3358eede0fe4c4acc' }))
})

// 提交修改后的用户信息
const submitForm = async () => {
  const updatedData = {
    admin: value1.value,
    sex: value2.value,
    age: value3.value,
    address: value4.value,
    work: value5.value,
    landlord: imageUrl.value // 保持头像信息
  }
  try {
    const response = await axios.post(`http://localhost:3000/lx/updateuser/?id=${id}`, updatedData)
    if (response.data.code === 200) {
      ElMessage.success('个人信息更新成功')
      router.push('/mine')
    } else {
      ElMessage.error('个人信息更新失败')
    }
  } catch (error) {
    ElMessage.error('提交失败，请重试')
    console.error(error)
  }
}

// 文件上传之前的校验
const beforeUpload = (file: File) => {
  const fileExtension = file.name.split('.').pop()?.toLowerCase()

  // 判断文件是否为 .webp 格式
  if (fileExtension === 'webp') {
    ElMessage.error('该图片存在违规内容，请重新上传')
    return false // 阻止上传
  }

  // 可以根据需要进一步增加其他校验，例如文件大小等
  return true
}
</script>

<style>


* {
  padding: 0;
  margin: 0;
}

.uesrinfo {
  width: 100%;
  height: 100px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 0 10px #ccc;
  padding: 20px;
  margin: 20px auto;
  text-align: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  border-radius: 50%;
  width: 100px;
  height: 100px;
  margin-top: 40px;
  margin-left: calc(50% - 50px);
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  border-radius: 50%;
  margin-left: calc(50% - 50px);
}
</style>
